class User < ActiveRecord::Base
  
  attr_accessible :login, :email, :password, :password_confirmation, :name 
  
  has_many :comments
  has_many :posts
  
  # will_paginate plugin
  cattr_reader :per_page
  @@per_page = 20
    
  validates_confirmation_of :password
  validates_uniqueness_of :login
  
  validates_format_of :password, :name, :with => /^[^\<\>]*$/
  validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+.)+[a-zA-Z]{2,})$/, :message => "must be an email address" 
  validates_format_of :login, :with => /^[0-9A-Za-z]*$/, :message => "must contain only letters and numbers"
  validates_length_of :login, :email, :password, :minimum => 5
  
  def before_create  
    require 'digest/sha1'
    require 'base64'
    self.name = self.login if self.name.blank?
    self.login = self.login.downcase
    self.email = self.email.downcase
    self.password_salt = [Array.new(6){rand(256).chr}.join].pack("m").chomp
    self.password = Base64.encode64(Digest::SHA1.digest(self.password.downcase + self.password_salt)).strip
    logger.info "Creating user"
  end
  
  def encrypt_password
    logger.info "Encrypting password"
    self.password_salt = [Array.new(6){rand(256).chr}.join].pack("m").chomp
    self.password = Base64.encode64(Digest::SHA1.digest(self.password.downcase + self.password_salt)).strip
  end
  
  def self.authenticate(user)
    require 'digest/sha1'
    require 'base64'
    
    return false unless user[:login] and user[:password]
    
    login = user[:login].downcase
    password = user[:password].downcase
    
    user = User.find_by_login(login) 
    
    logger.info "Authenticating #{login} (#{user.id})"  

    if user and Base64.encode64(Digest::SHA1.digest(password + user.password_salt)).strip == user.password
      logger.info "Authentication successful."
      return true
    else 
      logger.info "Can not authenticate the user, password mismatch."
      return false
    end
  end

  def forget_me
    logger.info("Forgetting users cookie")
    self.update_attributes(:remember_token_expires => nil, :remember_token => nil )
  end
  
end
